/**
 * Created by houjianhui on 2017/7/19.
 */

'use strict';
angular.module('wmsApp', ['ui.router', 'wms.controllers', 'wms.services', 'wms.filter', 'ngDialog', 'restangular', 'ui.select', 'wms.constant', 'wms.directives', 'ngCookies', 'angularFileUpload'])
    .constant('Settings', {
        Context: {
            path: contextPath
        }
    })
    .run(['$timeout', '$rootScope', '$location', '$state', 'Settings', 'Tools', 'constant', 'dropDownService', '$cookies', 'permissionsService', 'Restangular', 'FileUploader', '$timeout', 'ngDialog', function ($timeout, $rootScope, $location, $state, Settings, Tools, constant, dropDownService, cookies, permissionsService, restangular, FileUploader, timeout, ngDialog) {
        //关闭全局定时任务
        $timeout(function () {

            $('.layui-nav-tree a').click(function () {
                window.clearTimeout($rootScope.bs_timer1);
                window.clearTimeout($rootScope.bs_timer2);
                window.clearTimeout($rootScope.bs_timer3);
                window.clearTimeout($rootScope.bs_timer4);
                window.clearInterval($rootScope.bs_timer5);
                window.clearTimeout($rootScope.onwayIntertime);
            });
        }, 1000);


        $rootScope.$ = layui.jquery;
        layui.use(['form', 'laydate'], function () {
            $rootScope.$ = layui.jquery;
            $rootScope.form = layui.form();
            $rootScope.laydate = layui.laydate;
        });
        $rootScope.active = {
            tabAdd: function (id, titleName, content, url) {
                if (tabIsExit(titleName) > -1) {//判断是否有tab页，>-1存在
                    var tabId = getTabId(titleName);
                    $rootScope.elements.tabChange('tab_kas', tabId);
                    $rootScope.$('#index_content').addClass('layui-show');
                    $state.go(url);
                } else {
                    addTab(id, titleName, content, url);
                }
            }
        };

        //bs = bigScreen  大屏显示弹框设置时间
        $rootScope.bs_intervalTime = 10;   //默认10分钟


        $rootScope.bs_set_intervalTime = function () {
            ngDialog.open({
                template: "/templates/bigScreen/components/setIntervalTime.html",
                controller: "nullCtrl",
                title: '设置列表刷新时间',
                width: 319,
                height: 200
            });
        };

        // 获取当前时间
        $rootScope.getNowFormatDate = function () {
            var date = new Date();
            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var scd = '';
            if (date.getSeconds() >= 0 && date.getSeconds() <= 9) {
                scd = "0" + date.getSeconds();
            } else {
                scd = date.getSeconds();
            }
            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + scd;
            return currentdate;
        };

        //刷新事件(刷新，默认显示首页)
        /* $rootScope.$on('$locationChangeStart', function (event) {
             var  go_href =$(".layui-tab").find("li.layui-this span").attr("data-url");
             if(!go_href){
                 $state.go('index');
             }else{
                 event.preventDefault();
             }
         });*/

        function addTab(id, titleName, content, url) {//添加tab页
            var title = '';
            title += '<span id = "' + id + '" data-url ="' + url + '">' + titleName + '</span>';
            title += '<i class="layui-icon layui-unselect layui-tab-close" data-id ="' + id + '">&#x1006;</i>';
            var div = 'div_' + id;
            //添加tab
            $rootScope.elements.tabAdd('tab_kas', {
                title: title,
                id: id
            });

            $rootScope.$('.layui-tab-content').children('div.layui-tab-item').eq(1).remove();
            $rootScope.$('#index_content').addClass('layui-show');

            $rootScope.elements.tabChange('tab_kas', id);

            $rootScope.$('.layui-tab').find('li').children('i.layui-tab-close[data-id=' + id + ']').on('click', function () {
                $rootScope.elements.tabDelete("tab_kas", $(this).parent('li').attr('lay-id')).init();//关闭tab_title
                //点击x，关闭tab页
                var go_href = $(".layui-tab").find("li.layui-this span").attr("data-url");
                if (!go_href) {
                    $state.go('index');
                } else {
                    $state.go(go_href);
                }
            });
            //点击tab，进行切换
            $rootScope.$('.layui-tab').find('li[lay-id=' + id + ']').bind('click', function () {
                var tab_url = $(this).find('span').attr('data-url');
                $state.go(tab_url);//切换tab页
            });
            $state.go(url);//切换首页
        }

        function getTabId(title) {//获取tab页的id
            var tabId = -1;
            $rootScope.$('.layui-tab').find('li').each(function (i, e) {
                var $cite = $(this).children('span');
                if ($cite.text() === title) {
                    tabId = $(this).attr('lay-id');
                }
                ;
            });
            return tabId;
        }

        function tabIsExit(title) {//获取tab页是否存在，存在1，不存在-1
            var tabIndex = -1;
            $rootScope.$('.layui-tab').find('li').each(function (i, e) {
                var $cite = $(this).children('span');
                if ($cite.text() === title) {
                    tabIndex = i;
                }
                ;
            });
            return tabIndex;
        }

        // 初始化banner
        function initNav() {
            //获取用户权限
            permissionsService.getPermissListByUserId($rootScope.userInfo.id)
                .then(function (result) {
                    if (result.success) {
                        var menuList = new Array();
                        if (!result.data) {
                            $rootScope.Tools.alert('用户暂无权限');
                            return;
                        }
                        for (var i = 0; i < result.data.length; i++) {
                            var menu = {
                                title: result.data[i].name,
                                icon: 'fa-cogs',
                                default: false,
                                children: []
                            };
                            if (result.data[i].childPermiss) {
                                for (var j = 0; j < result.data[i].childPermiss.length; j++) {
                                    menu.children.push({
                                        id: result.data[i].childPermiss[j].id,
                                        title: result.data[i].childPermiss[j].name,
                                        icon: "fa-check-square-o",
                                        href: result.data[i].childPermiss[j].url
                                    })
                                }
                            }
                            menuList.push(menu);
                        }

                        $rootScope.menuList = menuList;
                        layui.use(['element'], function () {
                            $rootScope.elements = layui.element();
                        });
                    } else {
                        $rootScope.Tools.alert(result.message);
                    }
                })

            /*$.ajax({
                url: 'data/nav_data.json',
                type: 'GET',
                async: false,
                dataType: 'json',
                success: function (result, status, xhr) {
                    $rootScope.navList = result;
                    if (result != null) {
                        angular.forEach(result, function (item) {
                            if (item.default) {
                                initMenu(item.id);
                            }
                        })
                    }
                }
            });*/
        }

        /*function initMenu(id) {
            $.ajax({
                url: 'data/menu_data.json',
                type: 'GET',
                async: false,
                dataType: 'json',
                success: function (result, status, xhr) {
                    if (result != null) {
                        angular.forEach(result, function (item) {
                            if (item.id == id) {
                                $rootScope.menuList = item.list;
                            }
                        })
                    }
                }
            });
        }*/

        $rootScope.totalPage = 0;
        $rootScope.pageNo = 1;
        $rootScope.rootNewClip = function (obj, fun) {
            layui.use(['laypage'], function () {
                var laypage = layui.laypage;
                laypage({
                    cont: $(obj)
                    , pages: $rootScope.totalPage
                    , last: "" + $rootScope.totalPage + " 页，共" + $rootScope.totalRecord + " 条记录"
                    , skip: true
                    , curr: $rootScope.curr,
                    jump: function (obj, first) {
                        if (!first) {
                            //保存当前的页码，以备刷新当前页
                            $rootScope.curr = obj.curr;
                            fun(obj.curr);
                        }
                    }
                });
            })
        };

        // 注销
        $rootScope.logOut = function () {
            location.href = '/';
        };
        //设置工具类 可以直接访问
        $rootScope.Tools = Tools;
        //设置常量类 可以直接访问
        $rootScope.constant = constant;
        // 下拉service
        $rootScope.dropDownService = dropDownService;

        $rootScope.contextPath = Settings.Context.path;

        //用户信息
        $rootScope.userInfo = cookies.getObject('user');
        if (!$rootScope.userInfo) {   //如果没有登陆信息 返回登陆
            location.href = '/';
        }

        //设置restangular header
        restangular.addFullRequestInterceptor(function (element, operation, route, url, headers, params, httpConfig) {
            if (headers) {
                headers.whCode = $rootScope.userInfo.whCode;
                headers.token = $rootScope.userInfo.token;
                headers.userId = $rootScope.userInfo.id;
            } else {
                headers = {
                    whCode: $rootScope.userInfo.whCode,
                    token: $rootScope.userInfo.token,
                    userId: $rootScope.userInfo.id
                }
            }
            return {
                headers: headers
            };
        });

        //上传
        $rootScope.uploader = new FileUploader({
            queueLimit: 1,
            removeAfterUpload: true
        });
        $rootScope.setUploaderParam = function (url, paramName, callback) {
            $rootScope.uploader.url = Settings.Context.path + url;
            $rootScope.uploader.alias = paramName;
            $rootScope.uploader.headers.whCode = $rootScope.userInfo.whCode;
            $rootScope.uploader.headers.token = $rootScope.userInfo.token;
            if (callback) {
                $rootScope.uploader.onSuccessItem = callback;
            } else {
                $rootScope.uploader.onSuccessItem = function (fileItem, response, status, headers) {
                    layui.use('layer', function () {
                        var layer = layui.layer;
                        layer.closeAll();
                    });
                    if (status == 200 && response.success) {
                        $rootScope.Tools.alert(response.message);
                    } else {
                        $rootScope.Tools.alert(response.message);
                    }
                }
            }
        }
        $rootScope.uploader.onCompleteItem = function (item, response, status, headers) {
            $rootScope.uploader.clearQueue();
            $rootScope.uploader.cancelAll();
        }
        $rootScope.uploadAll = function () {
            timeout(function () {
                $rootScope.uploader.uploadAll();
            }, 100)
        }
        initNav();
    }])
    .config(['$stateProvider', '$urlRouterProvider', '$httpProvider', '$locationProvider', 'RestangularProvider', 'Settings', function ($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider, RestangularProvider, Settings) {

        $stateProvider
            .state('index', {   //主页
                url: '/index',
                templateUrl: 'templates/index.html'
            }).state('asn', {   //asn管理
            controller: 'asnCtrl',
            url: '/asn',
            templateUrl: 'templates/inStorageManagement/asnManagement/asn-list.html'
        }).state('in-storage-bill', {   //入库单管理
            controller: 'inStorageBillCtrl',
            url: '/in-storage-bill',
            templateUrl: 'templates/inStorageManagement/inStorageBill/in-storage-bill-list.html'
        }).state('input-work', {    //入库作业管理
            controller: 'inputWorkCtrl',
            url: '/input-work',
            templateUrl: 'templates/inStorageManagement/inputWork/input-work-list.html'
        }).state('input-work-receiving-quality', {    //入库管理收货质检
            controller: 'inputWorkReceivingQualityCtrl',
            url: '/input-work-receiving-quality',
            templateUrl: 'templates/inStorageManagement/inputWork/receiving-quality-testing-form.html'
        }).state('inventory-records-query', {    //入库记录查询
            controller: 'inventoryRecordsQueryCtrl',
            url: '/inventory-records-query',
            templateUrl: 'templates/inStorageManagement/inventoryRecordsQuery/inventory-records-query-list.html'
        }).state('boardCar-inventory-registration', {   //板车入场登记
            //boardCar-inventory-registration
            controller: 'boardCarInventoryRegistrationCtrl',
            url: '/boardCar-inventory-registration',
            templateUrl: 'templates/inStorageManagement/boardCar-inventory-registration/index.html'
        })
            .state('shipment-plan', {  //发运计划管理
                url: '/shipment-plan',
                templateUrl: 'templates/warehouseManagement/shipmentPlan/shipment-plan-list.html',
                controller: 'shipmentPlanCtrl'
            }).state('shipment-plan-reject', {  //发运计划驳回
            url: '/shipment-plan-reject',
            templateUrl: 'templates/warehouseManagement/shipmentPlanReject/shipment-plan-reject-list.html',
            controller: 'shipmentPlanRejectCtrl'
        }).state('outbound-order', {  //备料计划管理
            url: '/outbound-order',
            templateUrl: 'templates/warehouseManagement/outboundOrder/outbound-order-list.html',
            controller: 'outboundOrderCtrl'
        }).state('outbound-order-key', {  //备料钥匙领取
            url: '/outbound-order-key',
            templateUrl: 'templates/warehouseManagement/outboundOrderKey/outbound-order-key.html',
            controller: 'outboundOrderKeyCtrl'
        }).state('warehouse', {  //出库作业管理
            url: '/warehouse',
            templateUrl: 'templates/warehouseManagement/warehouse/warehouse-list.html',
            controller: 'warehouseCtrl'
        }).state('wmsPreparationPlan', {
            url: '/wmsPreparationPlan',
            templateUrl: 'templates/warehouseManagement/wmsPreparationPlan/index.html',
            controller: 'wmsPreparationPlanCtrl'
        }).state('outbound-print-receipt', {  //出库交接单打印
            url: '/outbound-print-receipt',
            templateUrl: 'templates/warehouseManagement/outboundPrintReceipt/outbound-print-receipt-list.html',
            controller: 'outboundPrintReceiptCtrl'
        }).state('warehouse-record', {  //出库记录查询
            url: '/warehouse-record',
            templateUrl: 'templates/warehouseManagement/warehouseRecord/warehouse-record-list.html',
            controller: 'warehouseRecordCtrl'
        }).state('scooter-off-registration', {  //板车离场登记
            url: '/scooter-off-registration',
            templateUrl: 'templates/warehouseManagement/scooterOffRegistration/scooter-off-registration-list.html',
            controller: 'scooterOffRegistrationCtrl'
        }).state('inventory-select', {  //库存查询
            url: '/inventory-select',
            templateUrl: 'templates/inventoryManagement/inventorySelect/inventory-select-list.html',
            controller: 'inventorySelectCtrl'
        }).state('inventory-overview', {    //库存概况
            url: '/inventory-overview',
            templateUrl: 'templates/inventoryManagement/inventoryOverview/inventory-overview-list.html'
        }).state('repair-bill', {    //维修单管理
            controller: 'repairBillCtrl',
            url: '/repair-bill',
            templateUrl: 'templates/maintenanceManagement/repairBill/repair-bill-list.html'
        }).state('abnormalManagement', { //异常管理
            controller: 'abnormalManagementCtrl',
            url: '/abnormalManagement',
            templateUrl: 'templates/maintenanceManagement/abnormalManagement/abnormalManagement.html'
        }).state('warehouse-maintenance', { //仓库维护
            controller: 'warehouseMaintenanceCtrl',
            url: '/warehouse-maintenance',
            templateUrl: 'templates/locationManagement/warehouseMaintenance/warehouse-maintenance-list.html'
        }).state('reservoir', { //库区管理
            controller: 'reservoirCtrl',
            url: '/reservoir',
            templateUrl: 'templates/locationManagement/reservoirManagement/reservoir-list.html'
        }).state('stock-unit', {    //库位管理
            controller: 'stockUnitCtrl',
            url: '/stock-unit',
            templateUrl: 'templates/locationManagement/stockUnitManagement/stock-unit-list.html'
        })
            .state('stock-unit-strategy', {    //库位策略管理
                controller: 'stockUnitStrategyCtrl',
                url: '/stock-unit-strategy',
                templateUrl: 'templates/strategyManagement/stockUnitStrategy/stock-unit-strategy-list.html'
            })
            .state('user', {    //用户
                controller: 'userCtrl',
                url: '/user',
                templateUrl: 'templates/systemManagement/userManagement/user-list.html'
            })
            .state('userForm', {    //用户 form
                controller: 'userFormCtrl',
                url: '/userForm/:userId',
                templateUrl: 'templates/systemManagement/userManagement/user-form.html'
            })
            .state('role', {    //角色
                controller: 'roleCtrl',
                url: '/role',
                templateUrl: 'templates/systemManagement/roleManagement/role-list.html'
            })
            .state('url', {    //角色
                controller: 'urlCtrl',
                url: '/url',
                templateUrl: 'templates/systemManagement/urlManagement/url-list.html'
            })
            .state('entrance-card', {    //门禁卡
                controller: 'entranceCardCtrl',
                url: '/entrance-card',
                templateUrl: 'templates/systemManagement/entranceCardManagement/entrance-card-list.html'
            })
            .state('borrowCarRegistration', {    //借车登记
                controller: 'borrowCarRegistrationCtrl',
                url: '/borrowCarRegistration',
                templateUrl: 'templates/vehicleBorrowingManagement/borrowCarRegistration.html'
            })
            .state('returnCarRegistration', {    //还车管理
                controller: 'returnCarRegistrationCtrl',
                url: '/returnCarRegistration',
                templateUrl: 'templates/vehicleBorrowingManagement/returnCarRegistration.html'
            })
            .state('borrowAndReturnRecordSearch', {    //车辆借还记录查询
                controller: 'borrowAndReturnRecordSearchCtrl',
                url: '/borrowAndReturnRecordSearch',
                templateUrl: 'templates/vehicleBorrowingManagement/borrowAndReturnRecordSearch.html'
            })
            .state('pickCar', {    // 大屏 提车
                controller: 'pickCarCtrl',
                url: '/pickCar',
                templateUrl: 'templates/bigScreen/pickCar.html'
            })
            .state('onWay', {    // 大屏 在途
                controller: 'onWayCtrl',
                url: '/onWay',
                templateUrl: 'templates/bigScreen/onWay.html'
            })
            .state('distribution', {    // 大屏 在途
                controller: 'distributionCtrl',
                url: '/distribution',
                templateUrl: 'templates/bigScreen/distribution.html'
            })
            .state('transferDepot', {    // 大屏 中转库1
                controller: 'transferDepotCtrl',
                url: '/transferDepot',
                templateUrl: 'templates/bigScreen/transferDepot.html'
            })
            .state('drayOutIn', {    // 大屏 中转2
                controller: 'drayOutInCtrl',
                url: '/drayOutIn',
                templateUrl: 'templates/bigScreen/drayOutIn.html'
            })
            .state('searchWaybillStatus', {    //大屏   运单状态查询
                controller: 'searchWaybillStatusCtrl',
                url: '/searchWaybillStatus',
                templateUrl: 'templates/bigScreen/searchWaybillStatus.html'
            })
            .state('operationOutOfStorage', {
                controller: 'operationOutOfStorageCtrl',
                url: '/operationOutOfStorage',
                templateUrl: 'templates/extraJmInterfaceOperation/operation-outofstorage-list.html'
            })
            .state('operationHandoverOrder', {
                controller: 'operationHandoverOrderCtrl',
                url: '/operationHandoverOrder',
                templateUrl: 'templates/extraJmInterfaceOperation/operation-handoverorder-list.html'
            })
            .state('inboundAllVerification', {
                controller: 'inboundAllVerificationCtrl',
                url: '/inboundAllVerification',
                templateUrl: 'templates/inventoryVerification/inboundall_verification_list.html'
            })
            .state('inboundJMVerification', {
                controller: 'inboundJMVerificationCtrl',
                url: '/inboundJMVerification',
                templateUrl: 'templates/inventoryVerification/inboundjm_verification_list.html'
            })
            .state('inboundJLVerification', {
                controller: 'inboundJLVerificationCtrl',
                url: '/inboundJLVerification',
                templateUrl: 'templates/inventoryVerification/inboundjl_verification_list.html'
            })
            .state('outboundAllVerification', {  //出库记录查询-所有
                url: '/outboundAllVerification',
                templateUrl: 'templates/inventoryVerification/outboundall_verification_list.html',
                controller: 'outboundAllVerificationCtrl'
            })
            .state('outboundJMVerification', {  //出库记录查询-君马
                url: '/outboundJMVerification',
                templateUrl: 'templates/inventoryVerification/outboundjm_verification_list.html',
                controller: 'outboundJMVerificationCtrl'
            })
            .state('outboundJLVerification', {  //出库记录查询-江铃
                url: '/outboundJLVerification',
                templateUrl: 'templates/inventoryVerification/outboundjl_verification_list.html',
                controller: 'outboundJLVerificationCtrl'
            })
            .state('inventoryAllVerification', {  //库存记录查询-所有
                url: '/inventoryAllVerification',
                templateUrl: 'templates/inventoryVerification/inventoryall_verification_list.html',
                controller: 'inventoryAllVerificationCtrl'
            })
            .state('inventoryJMVerification', {  //库存记录查询-君马
                url: '/inventoryJMVerification',
                templateUrl: 'templates/inventoryVerification/inventoryjm_verification_list.html',
                controller: 'inventoryJMVerificationCtrl'
            })
            .state('inventoryJLVerification', {  //库存记录查询-江铃
                url: '/inventoryJLVerification',
                templateUrl: 'templates/inventoryVerification/inventoryjl_verification_list.html',
                controller: 'inventoryJLVerificationCtrl'
            });

        $urlRouterProvider.otherwise('index');

        //配置restangular路径
        RestangularProvider.setDefaultHeaders({'Access-Control-Allow-Origin': '*'});
        RestangularProvider.setDefaultHeaders({'Cache-Control': 'max-age=1'});
        RestangularProvider.setBaseUrl(Settings.Context.path);

        // 使angular $http post提交和jQuery一致
        /* $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
         $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';*/

        // Override $http service's default transformRequest
        /* $httpProvider.defaults.transformRequest = [function (data) {
             /!**
              * The workhorse; converts an object to x-www-form-urlencoded serialization.
              * @param {Object} obj
              * @return {String}
              *!/
             var param = function (obj) {
                 var query = '';
                 var name, value, fullSubName, subName, subValue, innerObj, i;

                 for (name in obj) {
                     value = obj[name];

                     if (value instanceof Array) {
                         for (i = 0; i < value.length; ++i) {
                             subValue = value[i];
                             fullSubName = name + '[' + i + ']';
                             innerObj = {};
                             innerObj[fullSubName] = subValue;
                             query += param(innerObj) + '&';
                         }
                     } else if (value instanceof Object) {
                         for (subName in value) {
                             subValue = value[subName];
                             fullSubName = name + '[' + subName + ']';
                             innerObj = {};
                             innerObj[fullSubName] = subValue;
                             query += param(innerObj) + '&';
                         }
                     } else if (value !== undefined && value !== null) {
                         query += encodeURIComponent(name) + '='
                             + encodeURIComponent(value) + '&';
                     }
                 }

                 return query.length ? query.substr(0, query.length - 1) : query;
             };

             return angular.isObject(data) && String(data) !== '[object File]'
                 ? param(data)
                 : data;
         }];*/
    }])